module common.singleinstance;

private import core.sys.windows.windows;


class SingleInstance
{
	protected HWND FMutex;
	protected string FMutexName;

	public this()
	{
		FMutex = null;
	}

	public ~this()
	{
		if (FMutex !is null)
		{
			//ReleaseMutex(FMutex); // TODO:
			CloseHandle(FMutex);
			FMutex = null;
		}
	}
	
	public bool Initialize(in string name)
	{
		//var
		//  hndWnd: HWND;

		FMutexName = name ~ " Class";
		//FMutex = CreateMutex(null, false, PChar(FMutexName)); // TODO:
		// Check for errors

		// TODO:
		/+if (GetLastError == ERROR_ALREADY_EXISTS)
		{
			// Reset our mutext handle (just in case)
			FMutex = null;
			/*
			// The mutex already exists, which means an instance is already
			// running. Find the app and pop it up
			hndWnd := FindWindowEx( NULL, NULL, PChar(strID), nil );
			if ( hndWnd <> 0 ) then begin
			ShowWindow( hndWnd, SW_RESTORE );
			BringWindowToTop( hndWnd );
			SetForegroundWindow( hndWnd );
			end;
			// Return failure
			*/
			return true;
		}+/

		return false;
	}
}